package com.sunwayworld.baseline.framework.deviceDocking.handler;

import com.sunwayworld.baseline.framework.deviceDocking.dto.MessageDTO;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

/**
 * 仪器对接 通用消息处理器
 */
public class MessageHandler extends SimpleChannelInboundHandler<String> {

    private static final Logger log = LogManager.getLogger(MessageHandler.class);

    private String type;  // 接口类型，XY：血液分析仪，YP：雅培,ST_CO3

    private MessageObservable observer;

    public MessageHandler(MessageObservable observer, String type) {
        this.observer = observer;
        this.type = type;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String message) {
        log.info("ip: {} , 消息：{}" , ctx.channel().remoteAddress(), message);
        // 回复客户端
        observer.handle(new MessageDTO(type, ctx, message));  // 通知观察者处理消息
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        log.info("断开连接: ip:" + ctx.channel().remoteAddress());
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("成功建立连接,ip : {}", ctx.channel().remoteAddress());
        super.channelActive(ctx);
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public MessageObservable getObserver() {
        return observer;
    }

    public void setObserver(MessageObservable observer) {
        this.observer = observer;
    }

}
